package com.bq.gametrade.ui.activity;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.InputType;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;

import com.bq.gametrade.HttpLink;
import com.bq.gametrade.R;
import com.bq.gametrade.base.BaseActivity;
import com.bq.gametrade.bean.ResponseBean;
import com.bq.gametrade.bean.UserInfo;
import com.bq.gametrade.bean.UserInfoDetails;
import com.bq.gametrade.http.VRHttp;
import com.bq.gametrade.http.VRHttpListener;
import com.bq.gametrade.ui.dialog.LoadingProgressDialog;
import com.bq.gametrade.utils.Base64Util;
import com.bq.gametrade.utils.DateUtils;
import com.bq.gametrade.utils.MD5Util;
import com.bq.gametrade.utils.NetworkUtils;
import com.bq.gametrade.utils.StringUtils;
import com.bq.gametrade.view.PayPasswordValidationView;
import com.bumptech.glide.Glide;

import java.util.HashMap;
import java.util.Map;

public class FriendsTransferActivity extends BaseActivity implements View.OnClickListener{

    private ImageView back;
    private TextView tvTitle, tvTransferBill;
    private TextView tvFriendNickName, tvFriendBqAccount,tvMyAccountInfo;
    private EditText etTransferMoney;
    private LinearLayout layClear;
    private Button btnTransfer;
    private RadioGroup radioGroup;
    private RadioButton radioButton;
    private String transferType = "";
    private String friendName = "",friendBqAccount ="",friendAccount="",strFriendHeadImage="";
    private InputMethodManager inputMethodManager;
    private ImageView civHeadImage;
    private LoadingProgressDialog progressDialog;
    private UserInfoDetails userInfo;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_friendstransfer);
        if(application.isLogin()){
            userInfo = application.getUserInfo();
        }else {
            startActivity(new Intent(this, LoginActivity.class));
            finish();
        }
        progressDialog = new LoadingProgressDialog(this,"正在转账···");

        friendName = getIntent().getStringExtra("friendName");
        friendBqAccount = getIntent().getStringExtra("friendBqAccount");
        friendAccount = getIntent().getStringExtra("friendAccount");
        strFriendHeadImage = getIntent().getStringExtra("strFriendHeadImage");
        if(friendBqAccount.equals("")||friendName.equals("")||friendAccount.equals("")){
            toastShow("获取好友信息出错，请重试");
            finish();
        }
        inputMethodManager = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
        initView();
    }


    private void initView() {
        back = serchViewById(R.id.image_back);
        back.setOnClickListener(this);
        tvTitle = serchViewById(R.id.title_name);
        tvTitle.setText("转账");
        tvTransferBill = serchViewById(R.id.tv_transferBill);
        tvTransferBill.setOnClickListener(this);
        civHeadImage = serchViewById(R.id.civ_headImage);
        tvFriendNickName = serchViewById(R.id.tv_friendNickName);
        tvFriendBqAccount = serchViewById(R.id.tv_friendBqAccount);
        tvFriendNickName.setText(Base64Util.decodeStr(friendName));
        tvFriendBqAccount.setText(friendBqAccount);
        layClear = serchViewById(R.id.lay_clear);
        layClear.setOnClickListener(this);


        etTransferMoney = serchViewById(R.id.et_transferMoney);
        etTransferMoney.setInputType(InputType.TYPE_CLASS_NUMBER|InputType.TYPE_NUMBER_FLAG_DECIMAL);
        etTransferMoney.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence s, int i, int i1, int i2) {
                if (etTransferMoney.getText().toString().length() > 0) {
                    layClear.setVisibility(View.VISIBLE);
                } else {
                    layClear.setVisibility(View.INVISIBLE);
                }
                if (s.toString().contains(".")) {
                    if (s.length() - 1 - s.toString().indexOf(".") > 2) {
                        s = s.toString().subSequence(0,
                                s.toString().indexOf(".") + 3);
                        etTransferMoney.setText(s);
                        etTransferMoney.setSelection(s.length());
                    }
                }
                if (s.toString().trim().substring(0).equals(".")) {
                    s = "0" + s;
                    etTransferMoney.setText(s);
                    etTransferMoney.setSelection(2);
                }

                if (s.toString().startsWith("0")
                        && s.toString().trim().length() > 1) {
                    if (!s.toString().substring(1, 2).equals(".")) {
                        etTransferMoney.setText(s.subSequence(0, 1));
                        etTransferMoney.setSelection(1);
                        return;
                    }
                }
            }

            @Override
            public void afterTextChanged(Editable editable) {

            }
        });


        radioGroup = serchViewById(R.id.rg_pay);
        radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                radioButton = (RadioButton) findViewById(radioGroup.getCheckedRadioButtonId());
                inputMethodManager.hideSoftInputFromWindow(etTransferMoney.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
                if (radioButton.getText().toString().equals("转余额")) {
                    transferType = "1";
                } else {
                    transferType = "0";
                }
            }
        });

        btnTransfer = serchViewById(R.id.btn_transfer);
        btnTransfer.setOnClickListener(this);

        tvMyAccountInfo = serchViewById(R.id.tv_myAccountInfo);
        tvMyAccountInfo.setText("我的余额："+application.getUserInfo().userMoney+"元"+
                                "   我的鱼券："+application.getUserInfo().userCard+"个");

        Glide.with(FriendsTransferActivity.this).load(strFriendHeadImage).error(R.mipmap.user_headimg_gray).into(civHeadImage);
    }



    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.image_back:
                finish();
                break;
            case R.id.lay_clear:
                etTransferMoney.setText("");
                break;
            case R.id.tv_transferBill:
                startActivity(new Intent(FriendsTransferActivity.this, TransferBillActivity.class));
                break;
            case R.id.btn_transfer:

                if (TextUtils.isEmpty(etTransferMoney.getText().toString())) {
                    toastShow("转账金额还没有输入");
                    return;
                }
                if (etTransferMoney.getText().toString().equals("0")) {
                    toastShow("转账金额不正确");
                    return;
                }
                if (transferType.equals("")) {
                    toastShow("转账类型还没有选择");
                    return;
                }
                if (Double.parseDouble(etTransferMoney.getText().toString()) <= 0) {
                    toastShow("输入转账金额有误");
                    return;
                }
                if (transferType.equals("1") && Double.parseDouble(etTransferMoney.getText().toString()) > Double.parseDouble(application.getUserInfo().userMoney)) {
                    //转余额判断
                    toastShow("您没有那么多的余额了，快去充值吧");
                    return;
                }
                if (transferType.equals("0") &&  !StringUtils.isInteger(etTransferMoney.getText().toString())) {
                    //转余额判断
                    toastShow("转账鱼券必须为整数");
                    return;
                }

                if (transferType.equals("0") && Double.parseDouble(etTransferMoney.getText().toString()) > Double.parseDouble(application.getUserInfo().userCard)) {
                    //转余额判断
                    toastShow("您没有那么多的鱼券了，快去充值吧");
                    return;
                }
                if (!NetworkUtils.isNetworkAvailable(FriendsTransferActivity.this)) {
                    toastShow("当前网络异常");
                    return;
                }
                toPay(transferType,MD5Util.md5(DateUtils.getTimestamp()+application.getUserInfo().account+"android"));
                break;

        }
    }



    /**
     * 验证支付密码-----start
     */

    private void toPay(final String type,final String transId){
        final PayPasswordValidationView payPasswordValidationView = new PayPasswordValidationView(FriendsTransferActivity.this,userInfo,progressDialog);
        payPasswordValidationView.showAtLocation(FriendsTransferActivity.this.findViewById(R.id.activity_friendTransfer),
                Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0);
        payPasswordValidationView.backgroundAlpha(0.6f);
        payPasswordValidationView.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                payPasswordValidationView.backgroundAlpha(1f);
            }
        });

        payPasswordValidationView.setOnFinishInputPayPassword(new PayPasswordValidationView.OnPayPasswordInputFinish() {
            @Override
            public void inputFinish(String status) {
                if (status.equals("0")) {
                    toTransfer(type,transId);
                }
            }
        });
    }

    /**
     * end
     **/

    private void closeDialog(){
        if(progressDialog !=null){
            progressDialog.dismiss();
        }
    }



    private void toTransfer(String type,String transId) {
        Log.e("wu","+    "+transId);
        /**
         * 1:转账余额
         * 2：转账鱼券
         */
        Map<String, String> params = new HashMap<>();
        params.put("token", userInfo.token);
        params.put("account", friendAccount);
        params.put("num", etTransferMoney.getText().toString());
        params.put("type", type);
        params.put("transId",transId);
        VRHttp.sendRequest(FriendsTransferActivity.this, HttpLink.TRANDFER_MONRY_URL, params, new VRHttpListener() {
            @Override
            public void onSuccess(Object response, boolean isCache) {
                if (response != null) {
                    ResponseBean bean = (ResponseBean) response;
                    if (bean.status.equals("0")) {
                        toastShow("转账成功！");
                        finish();
                    } else if (bean.status.equals("99")) {
                        toastShow("登录超时请重新登陆");
                        application.setUserInfo(null);
                        startActivity(new Intent(FriendsTransferActivity.this, LoginActivity.class));
                    } else if (bean.status.equals("98")) {
                        toastShow("您的账号已在其它设备登录，请重新登录修改您的密码");
                        application.setUserInfo(null);
                        startActivity(new Intent(FriendsTransferActivity.this, LoginActivity.class));
                        finish();
                    } else {
                        toastShow("转账失败！");
                    }
                } else {
                    toastShow("转账失败！");

                }
            }

            @Override
            public void onError(String error) {
                super.onError(error);
                toastShow("转账失败！");
            }

            @Override
            public void onFinish() {
                super.onFinish();
                closeDialog();
            }
        });
    }

}
